#!/usr/bin/env node

import { Server } from '@modelcontextprotocol/sdk/server/index.js'
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
import {
  CallToolRequestSchema,
  ListToolsRequestSchema,
} from '@modelcontextprotocol/sdk/types.js'
import { SchemaGenerator } from './schema-generator.js'
import { GenerateOptions } from './types.js'

class SchemaGeneratorServer {
  private server: Server
  private generator: SchemaGenerator

  constructor() {
    this.server = new Server({
      name: 'schema-generator',
      version: '1.0.0',
    })

    // 初始化生成器，不再需要项目路径
    this.generator = new SchemaGenerator()
    this.setupHandlers()
  }

  private setupHandlers() {
    // 列出可用工具
    this.server.setRequestHandler(ListToolsRequestSchema, async () => {
      return {
        tools: [
          {
            name: 'scan_components',
            description: '获取所有演示Formily组件Schema',
            inputSchema: {
              type: 'object',
              properties: {},
              required: [],
            },
          },
          {
            name: 'generate_schema',
            description: '为指定组件生成JSON Schema',
            inputSchema: {
              type: 'object',
              properties: {
                componentName: {
                  type: 'string',
                  description: '组件名称',
                },
                options: {
                  type: 'object',
                  description: '生成选项',
                  properties: {
                    includeFormilyProps: {
                      type: 'boolean',
                      description: '是否包含Formily特定属性',
                      default: false,
                    },
                    includeValidation: {
                      type: 'boolean',
                      description: '是否包含验证规则',
                      default: false,
                    },
                    includeReactions: {
                      type: 'boolean',
                      description: '是否包含响应式规则',
                      default: false,
                    },
                  },
                },
              },
              required: ['componentName'],
            },
          },
          {
            name: 'generate_all_schemas',
            description: '生成所有组件的JSON Schema',
            inputSchema: {
              type: 'object',
              properties: {
                outputPath: {
                  type: 'string',
                  description: '输出文件路径',
                },
                options: {
                  type: 'object',
                  description: '生成选项',
                  properties: {
                    includeFormilyProps: {
                      type: 'boolean',
                      description: '是否包含Formily特定属性',
                      default: false,
                    },
                    includeValidation: {
                      type: 'boolean',
                      description: '是否包含验证规则',
                      default: false,
                    },
                    includeReactions: {
                      type: 'boolean',
                      description: '是否包含响应式规则',
                      default: false,
                    },
                    outputFormat: {
                      type: 'string',
                      enum: ['json', 'yaml'],
                      description: '输出格式',
                      default: 'json',
                    },
                  },
                },
              },
              required: ['outputPath'],
            },
          },
          {
            name: 'analyze_dependencies',
            description: '分析组件之间的依赖关系',
            inputSchema: {
              type: 'object',
              properties: {},
              required: [],
            },
          },
          {
            name: 'get_component_info',
            description: '获取指定组件的详细信息',
            inputSchema: {
              type: 'object',
              properties: {
                componentName: {
                  type: 'string',
                  description: '组件名称',
                },
              },
              required: ['componentName'],
            },
          },
        ],
      }
    })

    // 处理工具调用
    this.server.setRequestHandler(
      CallToolRequestSchema,
      async (request: any) => {
        const { name, arguments: args } = request.params

        if (!args) {
          throw new Error('缺少参数')
        }

        try {
          switch (name) {
            case 'scan_components':
              return await this.scanComponents()

            case 'generate_schema':
              return await this.generateSchema(
                args.componentName as string,
                (args.options as GenerateOptions) || {}
              )

            case 'generate_all_schemas':
              return await this.generateAllSchemas(
                args.outputPath as string,
                (args.options as GenerateOptions) || {}
              )

            case 'analyze_dependencies':
              return await this.analyzeDependencies()

            case 'get_component_info':
              return await this.getComponentInfo(args.componentName as string)

            default:
              throw new Error(`未知工具: ${name}`)
          }
        } catch (error) {
          return {
            content: [
              {
                type: 'text',
                text: `错误: ${
                  error instanceof Error ? error.message : String(error)
                }`,
              },
            ],
          }
        }
      }
    )
  }

  private async scanComponents() {
    const components = await this.generator.scanSchemas()

    return {
      content: [
        {
          type: 'text',
          text: `找到 ${components.length} 个演示组件:\n\n${components
            .map(
              (comp) =>
                `- ${comp.name} (${comp.category || 'demo'})${
                  comp.description ? `: ${comp.description}` : ''
                }`
            )
            .join('\n')}`,
        },
      ],
    }
  }

  private async generateSchema(
    componentName: string,
    options: GenerateOptions
  ) {
    const components = await this.generator.scanSchemas()
    const component = components.find((c) => c.name === componentName)

    if (!component) {
      throw new Error(`未找到组件: ${componentName}`)
    }

    const jsonSchema = this.generator.convertToJsonSchema(
      component.schema,
      options
    )

    return {
      content: [
        {
          type: 'text',
          text: `组件 ${componentName} 的JSON Schema:\n\n\`\`\`json\n${JSON.stringify(
            jsonSchema,
            null,
            2
          )}\n\`\`\``,
        },
      ],
    }
  }

  private async generateAllSchemas(
    outputPath: string,
    options: GenerateOptions
  ) {
    const schemas = await this.generator.generateAllSchemas(options)
    await this.generator.saveSchemas(schemas, outputPath, options)

    const componentNames = Object.keys(schemas)

    return {
      content: [
        {
          type: 'text',
          text: `成功生成 ${
            componentNames.length
          } 个演示组件的JSON Schema到 ${outputPath}\n\n包含的组件:\n${componentNames
            .map((name) => `- ${name}`)
            .join('\n')}`,
        },
      ],
    }
  }

  private async analyzeDependencies() {
    const dependencies = await this.generator.analyzeDependencies()

    const analysis = Object.entries(dependencies)
      .map(([component, deps]) => {
        if (deps.length === 0) return `- ${component}: 无依赖`
        return `- ${component}: ${deps.join(', ')}`
      })
      .join('\n')

    return {
      content: [
        {
          type: 'text',
          text: `演示组件依赖关系分析:\n\n${analysis}`,
        },
      ],
    }
  }

  private async getComponentInfo(componentName: string) {
    const components = await this.generator.scanSchemas()
    const component = components.find((c) => c.name === componentName)

    if (!component) {
      throw new Error(`未找到组件: ${componentName}`)
    }

    const dependencies = this.generator['extractDependencies'](component.schema)

    return {
      content: [
        {
          type: 'text',
          text:
            `演示组件信息: ${componentName}\n\n` +
            `路径: ${component.path}\n` +
            `分类: ${component.category || 'demo'}\n` +
            `描述: ${component.description || '无'}\n` +
            `依赖组件: ${
              dependencies.length > 0 ? dependencies.join(', ') : '无'
            }\n\n` +
            `Schema结构:\n\`\`\`json\n${JSON.stringify(
              component.schema,
              null,
              2
            )}\n\`\`\``,
        },
      ],
    }
  }

  async run() {
    const transport = new StdioServerTransport()
    await this.server.connect(transport)
    console.error('Schema生成器MCP服务已启动')
  }
}

// 启动服务器
const server = new SchemaGeneratorServer()
server.run().catch(console.error)
